﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ZombieManager : MonoBehaviour {

    public GameObject ZombiePrefab;
    public int maxZomOnScreen = 10;
    public float SpawnRate = 1;
    public Transform[] SpawnPoints;

    List<GameObject> Zombies = new List<GameObject>();
    float timer = 0;
    float cooldown = 0;

    void Awake()
    {
        cooldown = 1 / SpawnRate;
        timer = 0;
        Init();
    }

    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= cooldown)
        {
            timer = 0;
            int r = Random.Range(0, SpawnPoints.Length);
            Spawn(SpawnPoints[r].position);
        }
    }

    void Init()
    {
        Clear();

        for (int i = 0; i < maxZomOnScreen; i++)
        {
            GameObject zom = Instantiate(ZombiePrefab) as GameObject;
            //zom.transform.parent = transform;
            zom.SetActive(false);
            Zombies.Add(zom);
        }
    }

    void Clear()
    {
        for (int i = Zombies.Count; i > 0; i--)
        {
            Destroy(Zombies[i]);
        }
        Zombies.Clear();
    }

    void Spawn(Vector3 position)
    {
        for (int i = 0; i < Zombies.Count; i++)
        {
            if (!Zombies[i].activeInHierarchy)
            {
                Zombies[i].transform.position = position;
                Zombies[i].GetComponent<Character>().Awake();
                Zombies[i].SetActive(true);
                break;
            }
        }
    }
}
